package edu.whu.xterm.widget;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import edu.whu.xterm.Article;
import edu.whu.xterm.R;

public class ArticleAdapter extends BaseAdapter {

	private Context mContext;

	private List<Article> mData;

	private boolean hasMore;

	private int mHeadResource;

	private int mResource;

	public ArticleAdapter(Context ctx, List<Article> data, int headResource, int resource) {
		mContext = ctx;
		mData = data;
		this.mHeadResource = headResource;
		this.mResource = resource;
	}

	@Override
	public int getCount() {
		return mData.size() + (hasMore ? 1 : 0);
	}

	@Override
	public Article getItem(int position) {
		if (position < 0 || position >= mData.size())
			return null;
		return mData.get(position);
	}

	public void addItem(int position, Article data) {
		mData.add(position, data);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v;
		LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if (position == 0) {
			v = mInflater.inflate(mHeadResource, null);
		} else {
			ViewHolder holder;
			v = convertView;
			if (v == null) {
				v = mInflater.inflate(mResource, null);
				holder = new ViewHolder();
				holder.author = (TextView) v.findViewById(R.id.topic_reply_author);
				holder.time = (TextView) v.findViewById(R.id.topic_reply_time);
				holder.serial = (TextView) v.findViewById(R.id.topic_reply_serial);
				holder.content = (TextView) v.findViewById(R.id.topic_reply_content);
				holder.signature = (TextView) v.findViewById(R.id.item_signature_txt);
				holder.from = (TextView) v.findViewById(R.id.item_from);
				holder.ip = (TextView) v.findViewById(R.id.item_ip);
				v.setTag(holder);
			} else {
				holder = (ViewHolder) v.getTag();
			}
			Article data = getItem(position);

			holder.author.setText(data.author);
			holder.time.setText(data.time);
			holder.serial.setText("#" + (position + 1));
			holder.content.setText(data.content);
			holder.signature.setText(data.signature);
			holder.from.setText(data.from);
			holder.ip.setText(data.ip);
		}
		return v;
	}

	private static class ViewHolder {
		public TextView author;
		public TextView time;
		public TextView content;
		public TextView serial;
		public TextView signature;
		public TextView from;
		public TextView ip;
	}
}
